using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WpfApplication
{
    // 添加一个用于表示读取命令结果的类
    public class ReadCommandResult
    {
        // 命令是否成功执行
        public bool Success { get; set; }

        // 完整的响应数据
        public byte[] ResponseData { get; set; }

        // 如果是读取命令，这里包含提取的具体数据
        public object Value { get; set; }

        // 错误信息（如果有）
        public string ErrorMessage { get; set; }

        // 构造函数 - 失败情况
        public ReadCommandResult(string errorMessage)
        {
            Success = false;
            ErrorMessage = errorMessage;
        }

        // 构造函数 - 成功情况
        public ReadCommandResult(byte[] responseData, object value = null)
        {
            Success = true;
            ResponseData = responseData;
            Value = value;
        }
    }

    /// <summary>
    /// 命令信息类，包含命令数据和预期响应规则
    /// </summary>
    public class CommandInfo
    {
        // 命令唯一ID
        public Guid Id { get; } = Guid.NewGuid();

        // 命令数据
        public byte[] CommandData { get; set; }

        // 命令描述，用于日志
        public string Description { get; set; } = "";

        // 期望响应的前两个字节
        public byte[] ExpectedPrefix { get; set; } = new byte[] { 0x55, 0xAA };

        // 指定响应的第3、第4字节的验证规则
        public Func<byte, byte, bool> ValidateResponseBytes { get; set; }

        // 超时时间（毫秒）
        public int TimeoutMs { get; set; } = 3000;

        // 当前重试次数
        public int RetryCount { get; set; } = 0;

        // 最大重试次数
        public int MaxRetries { get; set; } = 3;

        // 重试间隔（毫秒）
        public int RetryIntervalMs { get; set; } = 1000;

        // 用于等待响应的TaskCompletionSource
        public TaskCompletionSource<byte[]> ResponseTask { get; } =
            new TaskCompletionSource<byte[]>();

        public CommandInfo(byte[] commandData, string description)
        {
            CommandData = commandData;
            Description = description;
        }

        // 创建此命令的副本（用于重试）
        public CommandInfo CreateCopy()
        {
            var copy = new CommandInfo(CommandData, Description)
            {
                ExpectedPrefix = this.ExpectedPrefix,
                ValidateResponseBytes = this.ValidateResponseBytes,
                TimeoutMs = this.TimeoutMs,
                MaxRetries = this.MaxRetries,
                RetryCount = this.RetryCount + 1,
                RetryIntervalMs = this.RetryIntervalMs,
            };
            return copy;
        }
    }

    public class SocketServer
    {
        private TcpListener _server;
        private CancellationTokenSource _cancellationTokenSource;
        private List<TcpClient> _clients = new List<TcpClient>();
        private bool _isServerRunning = false;
        private TaskCompletionSource<byte[]> _pendingResponse = null;

        // 命令队列
        private ConcurrentQueue<CommandInfo> _commandQueue = new ConcurrentQueue<CommandInfo>();

        // 当前正在执行的命令
        private CommandInfo _currentCommand = null;

        // 命令锁，确保同一时间只处理一条命令
        private SemaphoreSlim _commandSemaphore = new SemaphoreSlim(1, 1);

        // 是否正在处理命令
        private bool _isProcessingCommands = false;

        // 事件声明，用于通知 UI 更新
        public event Action<string> MessageLogged;
        public event Action ServerStarted;
        public event Action ServerStopped;
        public event Action<string, string> ClientConnected; // IP, Port
        public event Action<string, string> ClientDisconnected; // IP, Port
        public event Action<string, string, string> MessageReceived; // IP, Port, Message

        public bool IsRunning => _isServerRunning;

        public async Task StartAsync(int port)
        {
            try
            {
                if (port < 1 || port > 65535)
                {
                    LogMessage("无效的端口号。请输入1到65535之间的数字。");
                    return;
                }

                _cancellationTokenSource = new CancellationTokenSource();
                _server = new TcpListener(IPAddress.Any, port);
                _server.Start();
                _isServerRunning = true;

                LogMessage($"服务器已在端口 {port} 上启动");
                ServerStarted?.Invoke();

                await AcceptClientsAsync(_cancellationTokenSource.Token);
            }
            catch (Exception ex)
            {
                LogMessage($"启动服务器时出错: {ex.Message}");
                Stop();
            }
        }

        public void Stop()
        {
            if (_isServerRunning)
            {
                _cancellationTokenSource?.Cancel();

                foreach (var client in _clients)
                {
                    try
                    {
                        client.Close();
                    }
                    catch (Exception) { }
                }
                _clients.Clear();

                _server?.Stop();
                _isServerRunning = false;

                // 清除命令队列
                while (_commandQueue.TryDequeue(out var _)) { }
                _currentCommand = null;

                LogMessage("服务器已停止");
                ServerStopped?.Invoke();
            }
        }

        private async Task AcceptClientsAsync(CancellationToken cancellationToken)
        {
            try
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    TcpClient client = await _server.AcceptTcpClientAsync(cancellationToken);
                    _clients.Add(client);

                    var endpoint = (IPEndPoint)client.Client.RemoteEndPoint;
                    string ip = endpoint.Address.ToString();
                    string port = endpoint.Port.ToString();

                    LogMessage($"客户端已连接: {ip}:{port}");
                    ClientConnected?.Invoke(ip, port);

                    _ = HandleClientAsync(client, cancellationToken);
                }
            }
            catch (OperationCanceledException)
            {
                // 取消操作时预期的异常
            }
            catch (Exception ex)
            {
                if (!cancellationToken.IsCancellationRequested)
                {
                    LogMessage($"接受客户端连接时出错: {ex.Message}");
                }
            }
        }

        private async Task HandleClientAsync(TcpClient client, CancellationToken cancellationToken)
        {
            var endpoint = (IPEndPoint)client.Client.RemoteEndPoint;
            string ip = endpoint.Address.ToString();
            string port = endpoint.Port.ToString();
            byte[] buffer = new byte[4096];
            NetworkStream stream = client.GetStream();

            try
            {
                while (!cancellationToken.IsCancellationRequested && client.Connected)
                {
                    int bytesRead = await stream.ReadAsync(
                        buffer,
                        0,
                        buffer.Length,
                        cancellationToken
                    );
                    if (bytesRead == 0)
                    {
                        break; // 客户端断开连接
                    }

                    // 创建接收到的字节数组的副本
                    byte[] receivedData = new byte[bytesRead];
                    Array.Copy(buffer, receivedData, bytesRead);

                    string message = BitConverter.ToString(receivedData).Replace("-", " ");
                    LogMessage($"收到来自 {ip}:{port} 的消息: {message}");
                    MessageReceived?.Invoke(ip, port, message);

                    // 检查是否有当前等待响应的命令
                    if (_currentCommand != null && !_currentCommand.ResponseTask.Task.IsCompleted)
                    {
                        // 验证响应是否符合预期
                        if (ValidateResponse(receivedData, _currentCommand))
                        {
                            LogMessage($"命令 [{_currentCommand.Description}] 收到有效响应");
                            _currentCommand.ResponseTask.TrySetResult(receivedData);
                            // 处理队列中的下一条命令
                            _ = ProcessCommandQueueAsync();
                        }
                        else
                        {
                            LogMessage(
                                $"收到响应，但与命令 [{_currentCommand.Description}] 预期不符"
                            );
                            // 不完成命令，继续等待正确的响应
                        }
                    }
                    else if (_pendingResponse != null && !_pendingResponse.Task.IsCompleted)
                    {
                        // 兼容旧的响应处理机制
                        _pendingResponse.TrySetResult(receivedData);
                    }
                    else
                    {
                        // 将消息回显给所有客户端
                        await BroadcastToClientsAsync(receivedData, client);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                // 取消操作时预期的异常
            }
            catch (Exception ex)
            {
                if (!cancellationToken.IsCancellationRequested)
                {
                    LogMessage($"处理客户端 {ip}:{port} 时出错: {ex.Message}");
                }
            }
            finally
            {
                if (_clients.Contains(client))
                {
                    _clients.Remove(client);
                    LogMessage($"客户端断开连接: {ip}:{port}");
                    ClientDisconnected?.Invoke(ip, port);
                }

                client.Close();
            }
        }

        // 验证响应是否符合命令预期
        private bool ValidateResponse(byte[] response, CommandInfo command)
        {
            // 检查响应长度是否足够
            if (response == null || response.Length < 4)
                return false;

            // 检查前两个字节是否匹配预期前缀（通常是 55 AA）
            if (
                response[0] != command.ExpectedPrefix[0]
                || response[1] != command.ExpectedPrefix[1]
            )
                return false;

            // 如果有特定的验证规则，使用它来验证第3、第4个字节
            if (command.ValidateResponseBytes != null)
            {
                return command.ValidateResponseBytes(response[2], response[3]);
            }

            // 默认情况下，我们认为响应有效
            return true;
        }

        public async Task BroadcastMessageAsync(string message)
        {
            byte[] messageBytes = Encoding.UTF8.GetBytes(message);
            await BroadcastToClientsAsync(messageBytes);
            LogMessage($"广播消息: {message}");
        }

        private async Task BroadcastToClientsAsync(byte[] message, TcpClient excludeClient = null)
        {
            List<TcpClient> deadClients = new List<TcpClient>();

            foreach (var client in _clients)
            {
                if (client == excludeClient || !client.Connected)
                {
                    if (!client.Connected)
                    {
                        deadClients.Add(client);
                    }
                    continue;
                }

                try
                {
                    NetworkStream stream = client.GetStream();
                    await stream.WriteAsync(message, 0, message.Length);
                    await stream.FlushAsync();
                }
                catch (Exception)
                {
                    deadClients.Add(client);
                }
            }

            // 清理已断开连接的客户端
            foreach (var deadClient in deadClients)
            {
                if (_clients.Contains(deadClient))
                {
                    _clients.Remove(deadClient);
                    var endpoint = (IPEndPoint)deadClient.Client.RemoteEndPoint;
                    string ip = endpoint.Address.ToString();
                    string port = endpoint.Port.ToString();
                    LogMessage($"客户端断开连接: {ip}:{port}");
                    ClientDisconnected?.Invoke(ip, port);
                    deadClient.Close();
                }
            }
        }

        /// <summary>
        /// 发送联机命令并等待客户端响应
        /// </summary>
        /// <param name="clientIndex">客户端索引，默认为第一个连接的客户端</param>
        /// <param name="timeoutMs">超时时间（毫秒）</param>
        /// <param name="maxRetries">最大重试次数</param>
        /// <returns>成功返回true，失败返回false</returns>
        public async Task<bool> SendConnectionCommandAsync(
            int clientIndex = 0,
            int timeoutMs = 3000,
            int maxRetries = 3
        )
        {
            if (!_isServerRunning || _clients.Count == 0 || clientIndex >= _clients.Count)
            {
                LogMessage("无法发送联机命令：服务器未运行或没有连接的客户端");
                return false;
            }

            // 创建联机命令
            byte[] connectionCommand = new byte[] { 0x55, 0xAA, 0x01, 0x01, 0xFE, 0xFF };

            // 创建命令对象，设置响应验证规则
            var command = new CommandInfo(connectionCommand, "联机命令")
            {
                TimeoutMs = timeoutMs,
                MaxRetries = maxRetries,
                // 联机命令响应规则：前两个字节是 55 AA，第三第四个字节是 10 10
                ValidateResponseBytes = (byte3, byte4) => byte3 == 0x10 && byte4 == 0x10,
            };

            // 将命令加入队列并执行
            return await EnqueueAndExecuteCommandAsync(command, clientIndex);
        }

        /// <summary>
        /// 发送控制指令到客户端
        /// </summary>
        /// <param name="cmdType">指令类型(0x01-0x0A)</param>
        /// <param name="value">指令参数值，根据不同指令类型有不同含义：
        /// 0x01: 多路阀复位，不需要参数
        /// 0x02: 液路多路阀目标位置（脉冲数，0-65535）
        /// 0x04: 气路电磁阀控制模式（0-3）
        /// 0x05: 气泵开关（0=关闭，1=开启）
        /// 0x06: 反应缸加热目标温度（摄氏度）
        /// 0x07: 蜡缸加热目标温度（摄氏度）
        /// 0x08: 分配阀加热目标温度（摄氏度）
        /// 0x09: 接头加热目标温度（摄氏度）
        /// 0x0A: 气压压力矫正系数</param>
        /// <returns>命令执行结果</returns>
        public async Task<bool> SendControlCommand(
            byte cmdType,
            int value = 0,
            int clientIndex = 0,
            int timeoutMs = 3000,
            int maxRetries = 3
        )
        {
            byte[] command;
            string logMessage;

            switch (cmdType)
            {
                case 0x01: // 多路阀复位
                    command = new byte[] { 0x55, 0xAA, 0x02, 0x01, 0x01, 0xFE, 0xFF };
                    break;

                case 0x02: // 液路多路阀目标位置
                    command = new byte[]
                    {
                        0x55,
                        0xAA,
                        0x02,
                        0x02,
                        (byte)(value >> 8),
                        (byte)value,
                        0xFE,
                        0xFF,
                    };
                    break;

                case 0x04: // 气路电磁阀控制
                    command = new byte[] { 0x55, 0xAA, 0x02, 0x04, (byte)value, 0xFE, 0xFF };
                    break;

                case 0x05: // 气泵控制
                    command = new byte[] { 0x55, 0xAA, 0x02, 0x05, (byte)value, 0xFE, 0xFF };
                    break;

                case 0x06: // 反应缸加热温度
                    command = new byte[] { 0x55, 0xAA, 0x02, 0x06, (byte)value, 0xFE, 0xFF };
                    break;

                case 0x07: // 蜡缸加热温度
                    command = new byte[] { 0x55, 0xAA, 0x02, 0x07, (byte)value, 0xFE, 0xFF };
                    break;

                case 0x08: // 分配阀加热温度
                    command = new byte[] { 0x55, 0xAA, 0x02, 0x08, (byte)value, 0xFE, 0xFF };
                    break;

                case 0x09: // 接头加热温度
                    command = new byte[] { 0x55, 0xAA, 0x02, 0x09, (byte)value, 0xFE, 0xFF };
                    break;

                case 0x0A: // 气压压力矫正系数
                    command = new byte[] { 0x55, 0xAA, 0x02, 0x0A, (byte)value, 0xFE, 0xFF };
                    break;

                default:
                    throw new ArgumentException($"不支持的命令类型: {cmdType:X2}");
            }
            // 创建命令对象，设置响应验证规则
            var commandInfo = new CommandInfo(command, "控制命令")
            {
                TimeoutMs = timeoutMs,
                MaxRetries = maxRetries,
                // 修改验证规则：只要响应前三个字节是55 AA 20就认为成功
                ValidateResponseBytes = (byte3, byte4) => byte3 == 0x20,
            };
            return await EnqueueAndExecuteCommandAsync(commandInfo, clientIndex);
        }

        /// <summary>
        /// 发送通用命令并等待响应
        /// </summary>
        /// <param name="commandData">命令字节数组</param>
        /// <param name="description">命令描述</param>
        /// <param name="validateFunc">响应验证函数，检查第3和第4个字节</param>
        /// <param name="clientIndex">客户端索引</param>
        /// <param name="timeoutMs">超时时间</param>
        /// <param name="maxRetries">最大重试次数</param>
        /// <returns>成功返回true，失败返回false</returns>
        public async Task<bool> SendCommandAsync(
            byte[] commandData,
            string description,
            Func<byte, byte, bool> validateFunc,
            int clientIndex = 0,
            int timeoutMs = 3000,
            int maxRetries = 3
        )
        {
            if (!_isServerRunning || _clients.Count == 0 || clientIndex >= _clients.Count)
            {
                LogMessage($"无法发送命令 [{description}]：服务器未运行或没有连接的客户端");
                return false;
            }

            // 创建命令对象
            var command = new CommandInfo(commandData, description)
            {
                TimeoutMs = timeoutMs,
                MaxRetries = maxRetries,
                ValidateResponseBytes = validateFunc,
            };

            // 将命令加入队列并执行
            return await EnqueueAndExecuteCommandAsync(command, clientIndex);
        }

        /// <summary>
        /// 将命令加入队列并开始处理
        /// </summary>
        private async Task<bool> EnqueueAndExecuteCommandAsync(CommandInfo command, int clientIndex)
        {
            // 将命令加入队列
            _commandQueue.Enqueue(command);
            LogMessage($"命令 [{command.Description}] 加入队列");

            // 开始处理队列（如果尚未处理）
            if (!_isProcessingCommands)
            {
                _ = ProcessCommandQueueAsync();
            }

            try
            {
                // 等待命令执行完成或超时
                byte[] response = await await Task.WhenAny(
                    command.ResponseTask.Task,
                    Task.Delay(command.TimeoutMs).ContinueWith(_ => (byte[])null)
                );

                // 如果响应为 null，表示超时
                if (response == null)
                {
                    LogMessage($"命令 [{command.Description}] 执行超时");
                    command.ResponseTask.TrySetCanceled();
                    return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                LogMessage($"命令 [{command.Description}] 执行时出错: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 处理命令队列
        /// </summary>
        private async Task ProcessCommandQueueAsync()
        {
            // 如果已经有一个线程在处理队列，直接返回
            if (!await _commandSemaphore.WaitAsync(0))
                return;

            try
            {
                _isProcessingCommands = true;

                while (_commandQueue.TryDequeue(out CommandInfo command) && _isServerRunning)
                {
                    // 设置当前命令
                    _currentCommand = command;

                    // 获取客户端（暂时使用第一个客户端）
                    TcpClient client = _clients[0];
                    var endpoint = (IPEndPoint)client.Client.RemoteEndPoint;

                    try
                    {
                        // 记录发送的命令及重试信息
                        string retryInfo =
                            command.RetryCount > 0
                                ? $"(重试 {command.RetryCount}/{command.MaxRetries})"
                                : "";
                        string commandHex = BitConverter
                            .ToString(command.CommandData)
                            .Replace("-", " ");
                        LogMessage(
                            $"发送命令 [{command.Description}] {retryInfo} 到客户端 {endpoint.Address}:{endpoint.Port}: {commandHex}"
                        );

                        // 发送命令
                        NetworkStream stream = client.GetStream();
                        await stream.WriteAsync(command.CommandData, 0, command.CommandData.Length);
                        await stream.FlushAsync();

                        // 命令已发送，等待在 HandleClientAsync 中处理响应
                        // 此时不从队列中取下一个命令，直到收到响应或超时

                        // 等待命令完成或超时
                        await Task.WhenAny(
                            command.ResponseTask.Task,
                            Task.Delay(command.TimeoutMs)
                        );

                        // 如果命令未完成（超时），考虑重试
                        if (!command.ResponseTask.Task.IsCompleted)
                        {
                            if (command.RetryCount < command.MaxRetries)
                            {
                                LogMessage(
                                    $"命令 [{command.Description}] 等待响应超时，准备重试 ({command.RetryCount + 1}/{command.MaxRetries})"
                                );

                                // 创建命令副本，增加重试计数
                                var retryCommand = command.CreateCopy();

                                // 如果指定了重试间隔，则等待
                                if (command.RetryIntervalMs > 0)
                                {
                                    await Task.Delay(command.RetryIntervalMs);
                                }

                                // 将重试命令加入队列前端（优先处理）
                                _commandQueue.Enqueue(retryCommand);

                                // 对原命令设置为取消，因为我们已经计划进行重试
                                command.ResponseTask.TrySetCanceled();
                            }
                            else
                            {
                                LogMessage(
                                    $"命令 [{command.Description}] 达到最大重试次数 ({command.MaxRetries})，放弃执行"
                                );
                                command.ResponseTask.TrySetCanceled();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogMessage($"处理命令 [{command.Description}] 时出错: {ex.Message}");
                        command.ResponseTask.TrySetException(ex);
                    }
                }
            }
            finally
            {
                _currentCommand = null;
                _isProcessingCommands = false;
                _commandSemaphore.Release();
            }
        }

        /// <summary>
        /// 检查数组是否以指定的前缀开头
        /// </summary>
        private bool StartsWithByteArray(byte[] array, byte[] prefix)
        {
            // 检查是否为null或长度不足
            if (array == null || prefix == null || array.Length < prefix.Length)
                return false;

            // 比较前缀部分
            for (int i = 0; i < prefix.Length; i++)
            {
                if (array[i] != prefix[i])
                    return false;
            }

            return true;
        }

        private void LogMessage(string message)
        {
            MessageLogged?.Invoke(message);
        }

        /// <summary>
        /// 发送读取命令并获取具体数据
        /// </summary>
        /// <param name="readType">读取命令类型 (0x01-0x07)</param>
        /// <param name="clientIndex">客户端索引</param>
        /// <param name="timeoutMs">超时时间</param>
        /// <param name="maxRetries">最大重试次数</param>
        /// <returns>包含结果数据的ReadCommandResult对象</returns>
        public async Task<ReadCommandResult> SendReadCommandAsync(
            byte readType,
            int clientIndex = 0,
            int timeoutMs = 3000,
            int maxRetries = 3
        )
        {
            if (!_isServerRunning || _clients.Count == 0 || clientIndex >= _clients.Count)
            {
                return new ReadCommandResult("服务器未运行或没有连接的客户端");
            }

            // 根据读取类型构建命令
            byte[] command = new byte[] { 0x55, 0xAA, 0x03, readType, 0xFE, 0xFF };

            string description;

            switch (readType)
            {
                case 0x01:
                    description = "读取多路阀当前位置";
                    break;
                case 0x02:
                    description = "读取温度";
                    break;
                case 0x03:
                    description = "读取气压值";
                    break;
                case 0x04:
                    description = "读取液位信号";
                    break;
                case 0x05:
                    description = "查询多路阀复位";
                    break;
                case 0x06:
                    description = "加热信号查询";
                    break;
                case 0x07:
                    description = "反应缸盖打开关闭信号查询";
                    break;
                default:
                    return new ReadCommandResult($"不支持的读取命令类型: 0x{readType:X2}");
            }

            // 创建命令对象，验证规则为响应的前两个字节是55 AA，第三个字节是0x30
            var commandInfo = new CommandInfo(command, description)
            {
                TimeoutMs = timeoutMs,
                MaxRetries = maxRetries,
                ValidateResponseBytes = (byte3, byte4) => byte3 == 0x30,
            };

            try
            {
                // 将命令加入队列
                _commandQueue.Enqueue(commandInfo);
                LogMessage($"读取命令 [{description}] 加入队列");

                // 开始处理队列（如果尚未处理）
                if (!_isProcessingCommands)
                {
                    _ = ProcessCommandQueueAsync();
                }

                // 等待命令执行完成或超时
                byte[] response = await await Task.WhenAny(
                    commandInfo.ResponseTask.Task,
                    Task.Delay(timeoutMs).ContinueWith(_ => (byte[])null)
                );

                // 处理超时情况
                if (response == null)
                {
                    LogMessage($"读取命令 [{description}] 执行超时");
                    commandInfo.ResponseTask.TrySetCanceled();
                    return new ReadCommandResult("命令执行超时");
                }

                // 提取响应数据
                object extractedValue = ExtractValueFromResponse(readType, response);

                return new ReadCommandResult(response, extractedValue);
            }
            catch (Exception ex)
            {
                LogMessage($"执行读取命令时出错: {ex.Message}");
                return new ReadCommandResult($"命令执行出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 从响应数据中提取具体值
        /// </summary>
        /// <param name="readType">读取命令类型</param>
        /// <param name="response">完整响应数据</param>
        /// <returns>提取的具体值</returns>
        private object ExtractValueFromResponse(byte readType, byte[] response)
        {
            // 检查响应长度是否足够
            if (response == null || response.Length < 6)
            {
                return null;
            }

            try
            {
                switch (readType)
                {
                    case 0x01: // 多路阀当前位置
                        if (response.Length >= 8)
                        {
                            // 第5-6个字节表示多路阀位置
                            return (response[5] << 8) | response[6];
                        }
                        break;

                    case 0x02: // 读取温度
                        if (response.Length >= 9)
                        {
                            // 返回包含多个温度的字典
                            var temperatures = new Dictionary<string, int>
                            {
                                { "wax_temp", response[5] }, // 蜡缸温度
                                { "reactor_temp", response[6] }, // 缸缸温度
                                { "joint_temp", response[7] }, // 接头温度
                                { "valve_temp", response[8] }, // 多路阀温度
                            };
                            return temperatures;
                        }
                        break;

                    case 0x03: // 读取气压值
                        if (response.Length >= 8)
                        {
                            // 第5-6个字节表示气压值
                            return (response[5] << 8) | response[6];
                        }
                        break;

                    case 0x04: // 读取液位信号
                        if (response.Length >= 6)
                        {
                            var signals = new Dictionary<string, bool>();
                            byte signalByte = response[4];

                            signals["level1"] = (signalByte & 0x01) != 0; // 第0位 第一液位信号
                            signals["level2"] = (signalByte & 0x02) != 0; // 第1位 第二液位信号
                            signals["level3"] = (signalByte & 0x04) != 0; // 第2位 第三液位信号
                            signals["level4"] = (signalByte & 0x08) != 0; // 第3位 第四液位信号

                            return signals;
                        }
                        break;

                    case 0x05: // 查询多路阀复位
                        if (response.Length >= 6)
                        {
                            // 返回复位状态
                            return response[4] == 0x01;
                        }
                        break;

                    case 0x06: // 加热信号查询
                        if (response.Length >= 6)
                        {
                            // 返回一个字典，包含不同部位的加热信号
                            var heatSignals = new Dictionary<string, bool>();
                            byte signalByte = response[5];

                            heatSignals["wax_right"] = (signalByte & 0x08) != 0; // 蜡缸右加热信号
                            heatSignals["valve"] = (signalByte & 0x04) != 0; // 分配阀加热信号
                            heatSignals["reactor"] = (signalByte & 0x02) != 0; // 反应缸加热信号
                            heatSignals["wax_left"] = (signalByte & 0x01) != 0; // 蜡缸左加热信号

                            return heatSignals;
                        }
                        break;

                    case 0x07: // 反应缸盖打开关闭信号查询
                        if (response.Length >= 6)
                        {
                            // 返回一个字典，包含盖子信号
                            var coverSignals = new Dictionary<string, bool>();
                            byte signalByte = response[5];

                            coverSignals["handle_left"] = (signalByte & 0x02) != 0; // 开盖把手 左
                            coverSignals["handle_right"] = (signalByte & 0x01) != 0; // 开盖把手 右

                            return coverSignals;
                        }
                        break;
                }

                // 如果没有匹配的数据提取逻辑，返回原始响应数据的十六进制字符串
                return BitConverter.ToString(response).Replace("-", " ");
            }
            catch (Exception ex)
            {
                LogMessage($"提取响应值时出错: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 发送开机初始化参数命令
        /// </summary>
        /// <param name="yeluREST">多路阀复位值</param>
        /// <param name="yeluRestSpeed">多路阀复位速度</param>
        /// <param name="yeluWorkSpeed">多路阀工作速度</param>
        /// <param name="presCoef">压力矫正系数</param>
        /// <param name="clientIndex">客户端索引</param>
        /// <param name="timeoutMs">超时时间</param>
        /// <param name="maxRetries">最大重试次数</param>
        /// <returns>是否成功</returns>
        public async Task<bool> SendInitParamsCommand(
            int yeluREST = 1,
            int yeluRestSpeed = 1,
            int yeluWorkSpeed = 1,
            int presCoef = 1,
            int clientIndex = 0,
            int timeoutMs = 3000,
            int maxRetries = 3
        )
        {
            if (!_isServerRunning || _clients.Count == 0 || clientIndex >= _clients.Count)
            {
                LogMessage("无法发送开机初始化参数命令：服务器未运行或没有连接的客户端");
                return false;
            }

            // 构建初始化参数命令
            // 命令格式：55 AA 06 01 [YeLuREST高8位] [YeLuREST低8位] [YeLu_REST_SPD高8位] [YeLu_REST_SPD低8位]
            //          [YeLu_WORK_SPD高8位] [YeLu_WORK_SPD低8位] [PresCoef] FE FF
            byte[] command = new byte[]
            {
                0x55,
                0xAA, // 固定头
                0x06,
                0x01, // 命令码和子命令码
                (byte)(yeluREST >> 8),
                (byte)(yeluREST & 0xFF), // YeLuREST 多路阀复位值(uint16)
                (byte)(yeluRestSpeed >> 8),
                (byte)(yeluRestSpeed & 0xFF), // YeLu_REST_SPD 多路阀复位速度(uint16)
                (byte)(yeluWorkSpeed >> 8),
                (byte)(yeluWorkSpeed & 0xFF), // YeLu_WORK_SPD 多路阀工作速度(uint16)
                (byte)presCoef, // PresCoef 压力矫正系数(uint8)
                0xFE,
                0xFF, // 固定尾
            };

            // 创建命令对象，设置响应验证规则
            var commandInfo = new CommandInfo(command, "开机初始化参数")
            {
                TimeoutMs = timeoutMs,
                MaxRetries = maxRetries,
                // 初始化参数响应规则：前两个字节是 55 AA，第三第四个字节是 60 10
                ValidateResponseBytes = (byte3, byte4) => byte3 == 0x60 && byte4 == 0x10,
            };

            // 将命令加入队列并执行
            return await EnqueueAndExecuteCommandAsync(commandInfo, clientIndex);
        }
    }
}
